﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Reflection;


namespace NetalBase.Reflection
{
	class ReflectionHelper
	{
		public static string Get2CallingMethod()
		{
			StackTrace stackTrace = new StackTrace();

			return stackTrace.GetFrame(2).GetMethod().Name;
		}

		public static void FireEvent(object instance, string eventName, object[] parameters, Type type = null)
		{
			if (type == null)
				type = instance.GetType();

			var field = type.GetField(eventName,
				BindingFlags.Instance | BindingFlags.NonPublic);

			if (field == null)
			{
				if (type.BaseType == null)
					throw new ArgumentException("Cannot fire event");

				FireEvent(instance, eventName, parameters, type.BaseType);
				return;
			}

			var del = field.GetValue(instance) as MulticastDelegate;

			foreach (var d in del.GetInvocationList())
				d.Method.Invoke(d.Target, parameters);

		}
	}
}
